import router from './router'
// import { Message } from 'element-ui'
import {
  createDiscreteApi,
  darkTheme,
  lightTheme
} from "naive-ui";

import { isRelogin } from '@/utils/request'
import { setCache, getCache, removeCache, clearCache } from '@/utils/cache';
import { useAuthStore } from '@/store/auth';
import {TOKEN_KEY} from "@/enums/cacheEnum";


const whiteList = ['/login', '/register', '/']

const { message: Message, notification: Notification, dialog: Dialog, loadingBar } = createDiscreteApi(
    ["message", "dialog", "notification", "loadingBar"],
    {
      configProviderProps: { theme: darkTheme }
    }
);
window.$Message = Message;
window.$Notification = Notification;
window.$Dialog = Dialog;

router.beforeEach((to, from, next) => {
  // console.log('beforeEach--->to', to)
  // console.log('beforeEach--->from', from)
  // console.log('beforeEach--->next', next)

  const authStore = useAuthStore();
  loadingBar.start()
  if (true) {
    // message.info('登录成功')
  // if (getCache(TOKEN_KEY)) {
    /* has token*/
    if (to.path === '/login') { // 访问login
      next({ path: '/' })
      loadingBar.finish()
    } else if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      isRelogin.show = true
      // 验证token是否有效
      next()
      // authStore.dispatch('GetInfo').then(() => {
      //   isRelogin.show = false
      //   next({ ...to, replace: true })
      //
      // }).catch(err => {
      //   authStore.dispatch('LogOut').then(() => {
      //     Message.error(err)
      //     next({ path: '/' })
      //   })
      // })

      loadingBar.finish()

    }
  } else {
    next()
    // 没有token
    if (whiteList.indexOf(to.path) !== -1) {
      // 在免登录白名单，直接进入
      next()
    } else {
      next(`/login?redirect=${encodeURIComponent(to.fullPath)}`) // 否则全部重定向到登录页
      loadingBar.finish()
    }
  }
})

router.afterEach(() => {
  loadingBar.finish()
})
